﻿using OperationPlugins.Applications;
using OperationPlugins.Validators;
using System;
using System.Reflection;
using System.Web.Mvc;
using OperationPlugins.WebApp.Filters;

namespace OperationPlugins.WebApp.Controllers
{
    public class BlackBoxController : Controller
    {
        [HttpPost]
        [ApiAuthorize]
        public ActionResult Feed(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return Json(JsonValidationReply.Error("The content is null or an empty string."));
            }

            ApplicationRequestContext context = new ApplicationRequestContext { Headers = new HttpRequestHeaders(Request.Headers), Content = content };

            try
            {
                using (IApplicationInstance instance = ApplicationManager.CreateApplicationInstance(context, Assembly.GetExecutingAssembly()))
                {
                    using (IValidatorProxy validator = instance.CreateValidator())
                    {
                        MessageContainer result = validator.Validate();
                        return Json(JsonValidationReply.FromMessageContainer(result));
                    }
                }
            }
            catch (ApplicationManagerException e)
            {
                return Json(JsonValidationReply.FromException(e));
            }
            catch (ApplicationInstanceException e)
            {
                return Json(JsonValidationReply.FromException(e));
            }
            catch (Exception e)
            {
                return Json(JsonValidationReply.FromException(e));                
            }
        }

    }
}